package com.amex.uam.tasks;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.amex.uam.pojo.MSLogin;
import com.amex.uam.pojo.SecurityGroupBean;
import com.microstrategy.web.objects.WebIServerSession;

public class MDCache extends Thread{

	private static long INTERVAL = 10 * 60 * 1000 ; // interval 10 minutes to reload data
	private Map<String, SecurityGroupBean> scyGrpCache;
	
	private WebIServerSession session;
	
	private static MDCache instance;
	
	public static MDCache getInstance() {
		if (instance == null) {
			instance = new MDCache();
			instance.start();
		}
		return instance;
	}
	
	private MDCache() {
		this.setDaemon(true);
		scyGrpCache = new HashMap<String, SecurityGroupBean>();
	}
	public static void setInterval(long interval) {
		INTERVAL = interval;
	}
	public void addGroup(String groupName, SecurityGroupBean group) {
		scyGrpCache.put(groupName, group);
	}
	
	public SecurityGroupBean getGroup(String groupName) {
		return scyGrpCache.get(groupName);
	}
	
	public SecurityGroupBean getGroup(String groupName, WebIServerSession session) {
		
		if (session == null) {
			return scyGrpCache.get(groupName);
		}
		
		if (getGroup(groupName) == null) {
			SecurityGroupBean group = MDHelper.getGroups(groupName, session);
			this.addGroup(groupName, group);
		}  
		
		this.session = session;
		
		return getGroup(groupName);
	}
	
	@Override
	public void run() {
		while(true) {
			try{
				//XXX how to get session?
				if (this.session != null) {
					Iterator<String> it = scyGrpCache.keySet().iterator();
					while(it.hasNext()) {
						String groupName = it.next();
						SecurityGroupBean group = MDHelper.getGroups(groupName, session);
						if (group != null) {
							scyGrpCache.put(groupName, group);
						}
					}
				}
			} catch (Throwable t) {
				t.printStackTrace();
			}
			
			try {
				Thread.sleep(INTERVAL);
			} catch (InterruptedException e) {
			}

		}
	}
	
	public static void main(String[] args) throws Throwable {
		MSLogin user = new MSLogin();
		user.setServerName("localhost");
		user.setUsername("Administrator");
		user.setPassword("");
		//user.setProducts("MARC, ICARD, Dashboard");
		WebIServerSession session = MDHelper.getAdminSession(user);
		MDCache.setInterval(30 * 1000);
		while(true) {
			System.out.println(MDCache.getInstance().getGroup("MARC", session));
			Thread.sleep(10000);
		}
	}
}
